package br.edu.univas.jobmanager.dao;

import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.edu.univas.jobmanager.entity.Categoria;
import br.edu.univas.jobmanager.entity.Tarefa;

public class TarefaDAO extends GenericDAO<Tarefa, Integer>{

	public TarefaDAO() {
		super();
	}

	public TarefaDAO(EntityManager entityManager) {
		super(entityManager);
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Tarefa> getTarefasAbertasEPendentes(){
		String hql =" select t "+
						" from "+
		 				" Tarefa t "+
							" join " +
		 				" t.estado e "+ 
						" where "+
		 	            " e.idEstado <> 2"; 
		//ID2 2 a ID do estado concluido...
		
		Query query = getEntityManager().createQuery(hql);
		ArrayList<Tarefa> tarefas = (ArrayList<Tarefa>) query.getResultList();
		return tarefas;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Tarefa> filtraPorCategoria(Categoria categoria){
		if(categoria.getIdCategoria()==-1){
			return getTarefasAbertasEPendentes();
		}
		else{
			String hql = "select t " + " from Tarefa t " + " join t.estado e"
					+ " where t.categoria = :categoria " + " and "
					+ " e.idEstado <> 2";
			Query query = getEntityManager().createQuery(hql);
			query.setParameter("categoria", categoria);
			ArrayList<Tarefa> tarefas = (ArrayList<Tarefa>) query
					.getResultList();
			// for (Tarefa tarefa : tarefas) {
			// System.out.println(tarefa.getNome());
			// System.out.println(tarefa.getEstado().getTipo());
			// }
			return tarefas;
		}
	}
	public ArrayList<Tarefa> filtraTarefasAbertasEPendentes(String filtro){
		String hql =" select t "+
						" from "+
		 				" Tarefa t "+
							" join " +
		 				" t.estado e "+ 
						" where "+
		 	            " e.idEstado <> 2 and " +
		 	            " lower(t.nome) like(lower(:filtro))"; 
		//ID2 � a ID do estado concluido...
		
		Query query = getEntityManager().createQuery(hql);
		query.setParameter("filtro", "%" + filtro + "%");
		@SuppressWarnings("unchecked")
		ArrayList<Tarefa> tarefas = (ArrayList<Tarefa>) query.getResultList();
		return tarefas;
	}

	public Long getQuantidadedeTarefas() {

		String hql = "SELECT COUNT(t) from Tarefa t";
		Query query = getEntityManager().createQuery(hql);
		return  (Long) query.getSingleResult();
	}
}